package com.itheima.web;

import sun.misc.BASE64Encoder;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@WebServlet(name = "DownLoadServlet", urlPatterns = "/downLoadServlet")
public class DownLoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext sc = getServletContext();
        request.setCharacterEncoding("utf-8");
        String filename = request.getParameter("filename");
        String path = sc.getRealPath("/source/" + filename);
        System.out.println("path:" + path);
        String agent = request.getHeader("user-agent");
        System.out.println(agent);
        if (agent.equals("Firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
        } else {
            filename = URLEncoder.encode(filename, "utf-8");
        }
        String mimeType = sc.getMimeType(filename);
        System.out.println("MineType:" + mimeType);
        response.setContentType(mimeType);
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        FileInputStream fis = new FileInputStream(new File(path));
        OutputStream ots = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = fis.read(bytes)) != -1) {
            ots.write(bytes, 0, len);
        }
        ots.close();
        fis.close();
    }
}
